package org.hbbTlias2025.controller;


import lombok.extern.slf4j.Slf4j;
import org.hbbTlias2025.anno.LogOpreation;
import org.hbbTlias2025.pojo.Dept;
import org.hbbTlias2025.pojo.Result;
import org.hbbTlias2025.service.DeptService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController
//@Scope("prototype")
public class DeptController {

//    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(DeptController.class);

    public DeptController( ) {
        log.info("当前是执行了dept controller的构造函数，代表创建了这个bean");
    }

    Logger logger = log;

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result list() {
//        System.out.println("当前是要查询这个请求的所有数据");
        logger.info("当前是要查询这个请求的所有数据{}", 1);
        List<Dept> depts = deptService.findAll();
        return Result.success(depts);
    }

    @DeleteMapping
    @LogOpreation
    public Result delete(@RequestParam("id") Integer id) {
        logger.info("当前是要删除这个请求的数据{}", id);
        int i = deptService.deleteOne(id);
        if (i >= 1) {
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

    @PostMapping
    @LogOpreation
    public Result addOne(@RequestBody Dept dept) {
//        System.out.println("当前是要添加这个请求的数据" + dept);
        logger.info("当前是要添加这个请求的数据" + dept);
//        return Result.success();
        try {
            int i = deptService.addOne(dept);
            if (i >= 1) {
                return Result.success();
            }
        } catch (Exception e){
            return Result.error("添加失败");
        }
        return Result.error("添加失败");
    }

    @GetMapping("/{id}")

    public Result getOne(@PathVariable("id") Integer id, Principal principal) {
//        System.out.println("当前是要查询这个请求的数据"+ id);
        logger.info("当前是要查询这个请求的数据"+ id);
        try{
            Dept dept = deptService.getOne(id);
            if (dept == null){
                throw new NullPointerException(); // 抛出空指针异常，用于测试异常捕获h
            }
            return Result.success(dept);
        } catch (Exception e){
            return Result.error("查询失败");
        }
    }


    @PutMapping
    @LogOpreation
    public Result updateOne(@RequestBody Dept dept) {
//        System.out.println("当前是要修改这个请求的数据" + dept);
        logger.info("当前是要修改这个请求的数据" + dept);
        try {
            int i = deptService.updateOne(dept);
            if (i >= 1) {
                return Result.success();
            }
        } catch (Exception e){
            return Result.error("修改失败" + e);
        }
        return Result.error("修改失败??");
    }
}
